// 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果

import React, { useState, useEffect, useRef, memo } from 'react';
import { Layout, Menu, Card, Row, Col, Button, Space, Input, Table, Tag, Statistic } from 'antd';
import {
  DashboardOutlined,
  RobotOutlined,
  SettingOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import * as echarts from 'echarts';
import { timeUnits } from 'echarts/types/src/util/time.js';

const { Header, Sider, Content } = Layout;

// 创建一个接口来扩展echarts类型
interface ExtendedChart extends echarts.ECharts {
  cleanupEvents?: () => void;
}

// 网络拓扑图组件 - 使用memo避免不必要的重渲染
const NetworkTopology = memo(() => {
  const chartRef = useRef<HTMLDivElement | null>(null);
  const chartInstanceRef = useRef<ExtendedChart | null>(null);
  const initialized = useRef<boolean>(false);
  
  // 初始化图表
  useEffect(() => {
    // 如果已经初始化过，或者DOM元素不存在，直接返回
    if (initialized.current || !chartRef.current) {
      return;
    }
    
    // 延迟初始化，确保DOM准备好
    const timer = setTimeout(() => {
      const chartDom = chartRef.current;
      
      if (!chartDom || chartDom.offsetParent === null) {
        return;
      }
      
      try {
        // 确保没有遗留实例
        if (chartInstanceRef.current) {
          chartInstanceRef.current.dispose();
        }
        
        // 创建新实例
        const chart = echarts.init(chartDom, null, {
          renderer: 'canvas'
        }) as ExtendedChart;
        
        chartInstanceRef.current = chart;
        
        const option = {
          animation: false,
          title: {
            // text: '网络拓扑图',
            left: 'center'
          },
          tooltip: {},
          series: [{
            type: 'graph',
            layout: 'force',
            
            data: [
              { name: '节点1', value: 20, category: 0 },
              { name: '节点2', value: 15, category: 1 },
              { name: '节点3', value: 25, category: 1 },
            ],
            links: [
              { source: '节点1', target: '节点2' },
              { source: '节点2', target: '节点3' },
              { source: '节点1', target: '节点3' },
            ],
            categories: [
              { name: '主节点' },
              { name: '从节点' }
            ],
            roam: true,
            label: {
              show: true,
              position: 'right'
            },
            force: {
              repulsion: 100
            }
          }]
        };
        
        chart.setOption(option);
        
        // 设置resize处理
        const handleResize = () => {
          if (chart && !chart.isDisposed()) {
            try {
              chart.resize();
            } catch (e) {
              console.error("调整图表大小错误:", e);
            }
          }
        };
        
        // 添加防抖的resize处理
        let resizeTimeout: number | null = null;
        const debouncedResize = () => {
          if (resizeTimeout) {
            window.clearTimeout(resizeTimeout);
          }
          resizeTimeout = window.setTimeout(handleResize, 100);
        };
        
        window.addEventListener('resize', debouncedResize);
        
        // 设置ResizeObserver
        const observer = new ResizeObserver(debouncedResize);
        observer.observe(chartDom);
        
        // 标记为已初始化
        initialized.current = true;
        
        // 清理函数
        return () => {
          window.removeEventListener('resize', debouncedResize);
          observer.disconnect();
          
          // 延迟销毁图表，避免销毁时DOM操作错误
          setTimeout(() => {
            if (chartInstanceRef.current) {
              try {
                chartInstanceRef.current.dispose();
                chartInstanceRef.current = null;
              } catch (e) {
                console.error("销毁图表错误:", e);
              }
            }
          }, 0);
        };
      } catch (error) {
        console.error("初始化图表错误:", error);
      }
    }, 500);
    
    return () => {
      clearTimeout(timer);
    };
  }, []);
  
  return (
    <div 
      ref={chartRef}
      className="w-full flex-1 flex items-center justify-center" 
      style={{ minHeight: "300px", position: 'relative' }}
    ></div>
  );
});

const App: React.FC = () => {
  const [selectedMenu, setSelectedMenu] = useState('1');

  const columns = [
    {
      title: '节点ID',
      dataIndex: 'nodeId',
      key: 'nodeId',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '在线' ? 'success' : 'error'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '延迟',
      dataIndex: 'latency',
      key: 'latency',
    },
    {
      title: '带宽',
      dataIndex: 'bandwidth',
      key: 'bandwidth',
    },
  ];
  
  const data = [
    {
      key: '1',
      nodeId: 'Node-001',
      status: '在线',
      latency: '20ms',
      bandwidth: '100Mbps',
    },
    {
      key: '2',
      nodeId: 'Node-002',
      status: '在线',
      latency: '15ms',
      bandwidth: '150Mbps',
    },
    {
      key: '3',
      nodeId: 'Node-003',
      status: '离线',
      latency: '0ms',
      bandwidth: '0Mbps',
    },
  ];
  
  const renderContent = () => {
    switch (selectedMenu) {
      case '1':
        return (
          <div className="p-6 flex flex-col h-full">
            <Row gutter={[16, 16]} className="mb-6">
              <Col span={6}>
                <Card styles={{ body: { padding: 16 } }}>
                  <Statistic title="在线节点" value={8} suffix="/ 10" />
                </Card>
              </Col>
              <Col span={6}>
                <Card styles={{ body: { padding: 16 } }}>
                  <Statistic title="平均延迟" value={25} suffix="ms" />
                </Card>
              </Col>
              <Col span={6}>
                <Card styles={{ body: { padding: 16 } }}>
                  <Statistic title="网络带宽" value={1.2} suffix="Gbps" />
                </Card>
              </Col>
              <Col span={6}>
                <Card styles={{ body: { padding: 16 } }}>
                  <Statistic title="数据包丢失率" value={0.1} suffix="%" />
                </Card>
              </Col>
            </Row>
            <Row gutter={[16, 16]} className="flex-1">
              <Col span={16} className="h-full">
                <Card 
                  title="网络拓扑图" 
                  className="h-full flex flex-col" 
                  styles={{ header: { textAlign: 'center',fontSize: '20px',fontWeight: 'bold' }, body: { flex: 1, padding: 0, display: 'flex', flexDirection: 'column' } }}
                >
                  <NetworkTopology />
                </Card>
              </Col>
              <Col span={8} className="h-full">
                <Card title="节点状态" className="h-full overflow-auto" styles={{ header: { textAlign: 'center',fontSize: '20px',fontWeight: 'bold' }, body: { padding: 16 } }}>
                  <Table columns={columns} dataSource={data} pagination={false} />
                </Card>
              </Col>
            </Row>
          </div>
        );
      case '2':
        return (
          <div className="p-6 flex flex-col h-full">
            <Row gutter={[16, 16]} className="mb-6">
              <Col span={6}>
                <Card styles={{ body: { padding: 16 } }}>
                  <Statistic title="飞行状态" value="巡航中" />
                </Card>
              </Col>
              <Col span={6}>
                <Card styles={{ body: { padding: 16 } }}>
                  <Statistic title="当前高度" value={120} suffix="m" />
                </Card>
              </Col>
              <Col span={6}>
                <Card styles={{ body: { padding: 16 } }}>
                  <Statistic title="飞行速度" value={15.5} suffix="m/s" />
                </Card>
              </Col>
              <Col span={6}>
                <Card styles={{ body: { padding: 16 } }}>
                  <Statistic title="电池电量" value={85} suffix="%" />
                </Card>
              </Col>
            </Row>
            <Row gutter={[16, 16]} className="flex-1">
              <Col span={16} className="h-full">
                <Card title="实时飞行轨迹" className="h-full" styles={{ header: { textAlign: 'center',fontSize: '20px',fontWeight: 'bold' }, body: { height: 'calc(100% - 57px)', padding: 16 } }}>
                  <div className="flex flex-col h-full">
                    <div className="flex-1 bg-gray-100 rounded-lg mb-4" style={{ backgroundImage: 'url(https://mastergo.com/ai/api/search-image?query=aerial view of a modern city with streets and buildings shown from above, featuring a dynamic flight path visualization with clean minimalist style, soft pastel colors, perfect for a drone control interface background&width=800&height=400&orientation=landscape&flag=6d9fa85762b6d12b0545f4765cf103a3)', backgroundSize: 'cover', backgroundPosition: 'center', minHeight: "200px" }}>
                    </div>
                    <Space className="justify-center w-full">
                      <Button type="primary" icon={<i className="fas fa-plane-departure"/>} className="rounded-button-special whitespace-nowrap">起飞</Button>
                      <Button type="default" icon={<i className="fas fa-plane-arrival"/>} className="rounded-button-special whitespace-nowrap">降落</Button>
                      <Button type="default" icon={<i className="fas fa-pause"/>} className="rounded-button-special whitespace-nowrap">悬停</Button>
                      <Button type="default" icon={<i className="fas fa-home"/>} className="rounded-button-special whitespace-nowrap">返航</Button>
                      <Button danger icon={<i className="fas fa-stop"/>} className="rounded-button-special whitespace-nowrap">紧急停止</Button>
                    </Space>
                  </div>
                </Card>
              </Col>
              <Col span={8} className="h-full">
                <Card title="无人机控制面板" className="h-full" styles={{ header: { textAlign: 'center',fontSize: '20px',fontWeight: 'bold' }, body: { padding: 16 } }}>
                  <div className="space-y-4">
                    <div>
                      <div className="mb-2 font-medium">飞行高度调节 (m)</div>
                      <Space className="w-full justify-between items-center">
                        <Button icon={<i className="fas fa-minus"/>} className="rounded-button-special"/>
                        <span className="text-lg font-medium">120m</span>
                        <Button icon={<i className="fas fa-plus"/>} className="rounded-button-special"/>
                      </Space>
                    </div>
                    <div>
                      <div className="mb-2 font-medium">飞行速度调节 (m/s)</div>
                      <Space className="w-full justify-between items-center">
                        <Button icon={<i className="fas fa-minus"/>} className="rounded-button-special"/>
                        <span className="text-lg font-medium">15.5m/s</span>
                        <Button icon={<i className="fas fa-plus"/>} className="rounded-button-special"/>
                      </Space>
                    </div>
                    <div>
                      <div className="mb-2 font-medium">航向控制</div>
                      <div className="grid grid-cols-3 gap-2 w-full">
                        <div></div>
                        <Button icon={<i className="fas fa-arrow-up"/>} className="rounded-button-special"/>
                        <div></div>
                        <Button icon={<i className="fas fa-arrow-left"/>} className="rounded-button-special"/>
                        <Button icon={<i className="fas fa-dot-circle"/>} className="rounded-button-special"/>
                        <Button icon={<i className="fas fa-arrow-right"/>} className="rounded-button-special"/>
                        <div></div>
                        <Button icon={<i className="fas fa-arrow-down"/>} className="rounded-button-special"/>
                        <div></div>
                      </div>
                    </div>
                    <div>
                      <div className="mb-2 font-medium">云台控制</div>
                      <div className="grid grid-cols-3 gap-2">
                        <Button icon={<i className="fas fa-camera"/>} className="rounded-button-special whitespace-nowrap">拍照</Button>
                        <Button icon={<i className="fas fa-video"/>} className="rounded-button-special whitespace-nowrap">录像</Button>
                        <Button icon={<i className="fas fa-sync"/>} className="rounded-button-special whitespace-nowrap">校准</Button>
                      </div>
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
          </div>
        );
      case '3':
        return (
          <div className="p-6 flex flex-col h-full">
            <Row gutter={[16, 16]} className="mb-6">
              <Col span={24}>
                <Card title="网络参数配置" className="mb-6" styles={{ body: { padding: 16 } }}>
                  <Row gutter={[16, 16]}>
                    <Col span={6}>
                      <div className="space-y-4">
                        <div>
                          <div className="mb-2 font-medium">节点数量</div>
                          <Input prefix={<i className="fas fa-network-wired mr-2"/>} defaultValue="10" className="w-full"/>
                        </div>
                        <div>
                          <div className="mb-2 font-medium">路由协议</div>
                          <Button className="w-full text-left rounded-button-special whitespace-nowrap" icon={<i className="fas fa-route mr-2"/>}>
                            AODV <i className="fas fa-chevron-down float-right mt-1"/>
                          </Button>
                        </div>
                      </div>
                    </Col>
                    <Col span={6}>
                      <div className="space-y-4">
                        <div>
                          <div className="mb-2 font-medium">传输协议</div>
                          <Button className="w-full text-left rounded-button-special whitespace-nowrap" icon={<i className="fas fa-exchange-alt mr-2"/>}>
                            TCP <i className="fas fa-chevron-down float-right mt-1"/>
                          </Button>
                        </div>
                        <div>
                          <div className="mb-2 font-medium">MAC协议</div>
                          <Button className="w-full text-left rounded-button-special whitespace-nowrap" icon={<i className="fas fa-wifi mr-2"/>}>
                            802.11ax <i className="fas fa-chevron-down float-right mt-1"/>
                          </Button>
                        </div>
                      </div>
                    </Col>
                    <Col span={6}>
                      <div className="space-y-4">
                        <div>
                          <div className="mb-2 font-medium">信道带宽</div>
                          <Input prefix={<i className="fas fa-tachometer-alt mr-2"/>} defaultValue="20" suffix="MHz" className="w-full"/>
                        </div>
                        <div>
                          <div className="mb-2 font-medium">工作频率</div>
                          <Input prefix={<i className="fas fa-wave-square mr-2"/>} defaultValue="2.4" suffix="GHz" className="w-full"/>
                        </div>
                      </div>
                    </Col>
                    <Col span={6}>
                      <div className="space-y-4">
                        <div>
                          <div className="mb-2 font-medium">传输功率</div>
                          <Input prefix={<i className="fas fa-bolt mr-2"/>} defaultValue="20" suffix="dBm" className="w-full"/>
                        </div>
                        <div>
                          <div className="mb-2 font-medium">天线增益</div>
                          <Input prefix={<i className="fas fa-broadcast-tower mr-2"/>} defaultValue="2" suffix="dBi" className="w-full"/>
                        </div>
                      </div>
                    </Col>
                  </Row>
                  <Row className="mt-6">
                    <Col span={24}>
                      <Space className="w-full justify-end">
                        <Button icon={<i className="fas fa-undo"/>} className="rounded-button-special whitespace-nowrap">恢复默认</Button>
                        <Button type="primary" icon={<i className="fas fa-save"/>} className="rounded-button-special whitespace-nowrap">保存配置</Button>
                      </Space>
                    </Col>
                  </Row>
                </Card>
              </Col>
            </Row>
            <Row gutter={[16, 16]} className="flex-1">
              <Col span={12} className="h-full">
                <Card title="网络拓扑设置" className="h-full" styles={{ body: { padding: 16 } }}>
                  <div className="mb-4">
                    <div className="font-medium mb-2">拓扑类型</div>
                    <div className="grid grid-cols-3 gap-4">
                      <Card className="cursor-pointer border-blue-500" hoverable styles={{ body: { padding: 16 } }}>
                        <div className="text-center">
                          <i className="fas fa-project-diagram text-2xl mb-2 text-blue-500"/>
                          <div>网格拓扑</div>
                        </div>
                      </Card>
                      <Card className="cursor-pointer" hoverable styles={{ body: { padding: 16 } }}>
                        <div className="text-center">
                          <i className="fas fa-circle-notch text-2xl mb-2"/>
                          <div>环形拓扑</div>
                        </div>
                      </Card>
                      <Card className="cursor-pointer" hoverable styles={{ body: { padding: 16 } }}>
                        <div className="text-center">
                          <i className="fas fa-star text-2xl mb-2"/>
                          <div>星型拓扑</div>
                        </div>
                      </Card>
                    </div>
                    <div className="mt-4">
                      <div className="font-medium mb-2">拓扑参数</div>
                      <Row gutter={[16, 16]}>
                        <Col span={12}>
                          <div className="mb-2">节点间距 (m)</div>
                          <Input prefix={<i className="fas fa-arrows-alt-h mr-2"/>} defaultValue="100" className="w-full"/>
                        </Col>
                        <Col span={12}>
                          <div className="mb-2">覆盖范围 (m²)</div>
                          <Input prefix={<i className="fas fa-vector-square mr-2"/>} defaultValue="1000" className="w-full"/>
                        </Col>
                      </Row>
                    </div>
                  </div>
                </Card>
              </Col>
              <Col span={12} className="h-full">
                <Card title="高级设置" className="h-full" styles={{ body: { padding: 16 } }}>
                  <div className="space-y-4">
                    <div>
                      <div className="font-medium mb-2">QoS 设置</div>
                      <Row gutter={[16, 16]}>
                        <Col span={12}>
                          <div className="mb-2">最大延迟 (ms)</div>
                          <Input prefix={<i className="fas fa-clock mr-2"/>} defaultValue="200" className="w-full"/>
                        </Col>
                        <Col span={12}>
                          <div className="mb-2">丢包率阈值 (%)</div>
                          <Input prefix={<i className="fas fa-exclamation-triangle mr-2"/>} defaultValue="1" className="w-full"/>
                        </Col>
                      </Row>
                    </div>
                    <div>
                      <div className="font-medium mb-2">移动性模型</div>
                      <Button className="w-full text-left rounded-button-special whitespace-nowrap" icon={<i className="fas fa-running mr-2"/>}>
                        随机路点模型 <i className="fas fa-chevron-down float-right mt-1"/>
                      </Button>
                    </div>
                    <div>
                      <div className="font-medium mb-2">传播模型</div>
                      <Button className="w-full text-left rounded-button-special whitespace-nowrap" icon={<i className="fas fa-broadcast-tower mr-2"/>}>
                        自由空间传播模型 <i className="fas fa-chevron-down float-right mt-1"/>
                      </Button>
                    </div>
                    <div>
                      <div className="font-medium mb-2">干扰模型</div>
                      <Button className="w-full text-left rounded-button-special whitespace-nowrap" icon={<i className="fas fa-random mr-2"/>}>
                        加性高斯白噪声 <i className="fas fa-chevron-down float-right mt-1"/>
                      </Button>
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
          </div>
        );
      case '4':
        return (
          <div className="p-6 flex flex-col h-full">
            <Card title="系统日志" className="mb-6" styles={{ body: { padding: 16 } }}>
              <div className="flex justify-between mb-4">
                <Space>
                  <Button icon={<i className="fas fa-filter"/>} className="rounded-button-special whitespace-nowrap">过滤</Button>
                  <Button icon={<i className="fas fa-download"/>} className="rounded-button-special whitespace-nowrap">导出</Button>
                  <Button icon={<i className="fas fa-trash"/>} className="rounded-button-special whitespace-nowrap">清空</Button>
                </Space>
                <Space>
                  <Input.Search placeholder="搜索日志..." style={{ width: 250 }} />
                </Space>
              </div>
              <Table
                dataSource={[
                  {
                    key: '1',
                    time: '2024-01-20 10:30:25',
                    level: 'INFO',
                    module: '网络控制',
                    message: '系统启动完成，网络拓扑初始化成功',
                  },
                  {
                    key: '2',
                    time: '2024-01-20 10:30:28',
                    level: 'INFO',
                    module: '无人机控制',
                    message: '无人机节点 Node-001 已连接',
                  },
                  {
                    key: '3',
                    time: '2024-01-20 10:31:15',
                    level: 'WARNING',
                    module: '网络监控',
                    message: 'Node-003 响应超时，正在重试连接',
                  },
                  {
                    key: '4',
                    time: '2024-01-20 10:31:45',
                    level: 'ERROR',
                    module: '网络监控',
                    message: 'Node-003 连接失败，节点可能离线',
                  },
                  {
                    key: '5',
                    time: '2024-01-20 10:32:10',
                    level: 'INFO',
                    module: '系统配置',
                    message: '网络参数更新：传输功率调整为 20dBm',
                  }
                ]}
                columns={[
                  {
                    title: '时间',
                    dataIndex: 'time',
                    key: 'time',
                    width: 180,
                  },
                  {
                    title: '级别',
                    dataIndex: 'level',
                    key: 'level',
                    width: 100,
                    render: (level: string) => (
                      <Tag color={
                        level === 'ERROR' ? 'error' :
                        level === 'WARNING' ? 'warning' :
                        'success'
                      }>
                        {level}
                      </Tag>
                    ),
                  },
                  {
                    title: '模块',
                    dataIndex: 'module',
                    key: 'module',
                    width: 120,
                  },
                  {
                    title: '日志内容',
                    dataIndex: 'message',
                    key: 'message',
                  },
                ]}
                pagination={{
                  total: 50,
                  pageSize: 10,
                }}
              />
            </Card>
            <Row gutter={[16, 16]} className="flex-1">
              <Col span={12} className="h-full">
                <Card title="日志统计" className="h-full" styles={{ body: { padding: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-around', height: 'calc(100% - 57px)' } }}>
                  <div className="flex items-center justify-around h-full">
                    <Statistic title="总日志数" value={1234} prefix={<i className="fas fa-clipboard-list"/>} />
                    <Statistic title="今日新增" value={89} prefix={<i className="fas fa-plus-circle"/>} />
                    <Statistic title="错误日志" value={12} prefix={<i className="fas fa-exclamation-circle"/>} />
                    <Statistic title="警告日志" value={45} prefix={<i className="fas fa-exclamation-triangle"/>} />
                  </div>
                </Card>
              </Col>
              <Col span={12} className="h-full">
                <Card title="系统性能" className="h-full" styles={{ body: { padding: 16, display: 'flex', alignItems: 'center', height: 'calc(100% - 57px)' } }}>
                  <Row gutter={[16, 16]} className="h-full items-center">
                    <Col span={8}>
                      <Statistic title="CPU使用率" value={32} suffix="%" prefix={<i className="fas fa-microchip"/>} />
                    </Col>
                    <Col span={8}>
                      <Statistic title="内存使用率" value={45} suffix="%" prefix={<i className="fas fa-memory"/>} />
                    </Col>
                    <Col span={8}>
                      <Statistic title="磁盘使用率" value={28} suffix="%" prefix={<i className="fas fa-hdd"/>} />
                    </Col>
                  </Row>
                </Card>
              </Col>
            </Row>
          </div>
        );
      default:
        return <div className="p-6">开发中...</div>;
    }
  };
  
  return (
    <Layout className="min-h-screen h-screen flex flex-col">
      <Layout className="flex-1 flex overflow-hidden">
        <Sider width="11%" className="bg-white flex flex-col overflow-auto">
          <div className="py-4 flex items-center justify-center text-lg font-bold">
            ROS2-NS3 控制台
          </div>
          <Menu
            mode="inline"
            selectedKeys={[selectedMenu]}
            onClick={({ key }) => setSelectedMenu(key)}
            className="flex-1 overflow-auto"
            items={[
              {
                key: '1',
                icon: <DashboardOutlined />,
                label: '网络监控',
              },
              {
                key: '2',
                icon: <RobotOutlined />,
                label: '无人机控制',
              },
              {
                key: '3',
                icon: <SettingOutlined />,
                label: '网络配置',
              },
              {
                key: '4',
                icon: <FileTextOutlined />,
                label: '系统日志',
              },
            ]}
          />
        </Sider>
        <Layout className="flex-1 flex flex-col overflow-hidden">
          <Header className="bg-white px-4 flex items-center justify-between h-16">
            <Space>
              <span className="text-lg">系统状态: </span>
              <Tag color="success">运行中</Tag>
            </Space>
            <div className="flex items-center gap-4">
              <div className="flex items-center">
                <Input.Search placeholder="搜索..." className="w-64" style={{ verticalAlign: 'middle' }} />
              </div>
              <Button type="primary" className="rounded-button-special whitespace-nowrap">刷新数据</Button>
            </div>
          </Header>
          <Content className="bg-gray-50 flex-1 overflow-auto">
            {renderContent()}
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default App;
